import { useState, useRef, useEffect } from 'react'
import { Input, Button, Space, Spin, message, Avatar } from 'antd'
import { 
  SendOutlined, 
  UserOutlined, 
  RobotOutlined, 
  FileTextOutlined,
  PictureOutlined,
  CodeOutlined,
  TranslationOutlined,
  VideoCameraOutlined,
  FileOutlined,
  MoreOutlined,
  PaperClipOutlined,
  AudioOutlined
} from '@ant-design/icons'
import Typewriter from '../../components/Typewriter'
import './index.scss'

const { TextArea } = Input

const AITools = () => {
  const [messages, setMessages] = useState([])
  const [inputValue, setInputValue] = useState('')
  const [loading, setLoading] = useState(false)
  const messagesEndRef = useRef(null)
  const [showChat, setShowChat] = useState(false)

  // 自动滚动到底部
  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  // 发送消息
  const handleSend = async () => {
    if (!inputValue.trim()) {
      message.warning('请输入内容')
      return
    }

    setShowChat(true)

    // 添加用户消息
    const userMessage = {
      id: Date.now(),
      type: 'user',
      content: inputValue,
      time: new Date().toLocaleTimeString(),
    }

    setMessages(prev => [...prev, userMessage])
    setInputValue('')
    setLoading(true)

    // 模拟AI回复
    setTimeout(() => {
      const aiMessage = {
        id: Date.now() + 1,
        type: 'ai',
        content: '这是一个模拟的AI回复。在实际应用中，这里会调用AI接口获取真实的回复内容。您可以询问关于图书推荐、阅读建议、数据分析等问题。',
        time: new Date().toLocaleTimeString(),
      }
      setMessages(prev => [...prev, aiMessage])
      setLoading(false)
    }, 1000)
  }

  // 功能按钮
  const tools = [
    { icon: <FileTextOutlined />, label: '帮我写作', color: '#52c41a' },
    { icon: <PictureOutlined />, label: '图像生成', color: '#faad14' },
    { icon: <CodeOutlined />, label: '编程', color: '#1890ff' },
    { icon: <TranslationOutlined />, label: '翻译', color: '#722ed1' },
    { icon: <VideoCameraOutlined />, label: '视频生成', color: '#f5222d' },
    { icon: <FileOutlined />, label: 'AI PPT', color: '#fa8c16' },
    { icon: <MoreOutlined />, label: '更多', color: '#8c8c8c' },
  ]

  return (
    <div className="ai-tools-container">
      {!showChat ? (
        // 初始页面
        <div className="welcome-page">
          <h1 className="greeting">
            <Typewriter text="下午好，管理员" speed={100} />
          </h1>
          
          <div className="input-wrapper">
            <div className="input-box">
              <TextArea
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                placeholder="发消息或输入 / 选择话题"
                autoSize={{ minRows: 3, maxRows: 6 }}
                bordered={false}
                onPressEnter={(e) => {
                  if (!e.shiftKey) {
                    e.preventDefault()
                    handleSend()
                  }
                }}
              />
              <div className="input-footer">
                <Space size="middle">
                  <Button type="text" icon={<PaperClipOutlined />} size="small" />
                  <Button type="text" size="small">深度思考</Button>
                </Space>
                <Space size="small">
                  <Button type="text" icon={<AudioOutlined />} size="small" />
                  <Button
                    type="primary"
                    shape="circle"
                    icon={<SendOutlined />}
                    onClick={handleSend}
                    disabled={!inputValue.trim()}
                  />
                </Space>
              </div>
            </div>
          </div>

          <div className="tools-grid">
            {tools.map((tool, index) => (
              <div key={index} className="tool-item">
                <div className="tool-icon" style={{ color: tool.color }}>
                  {tool.icon}
                </div>
                <span className="tool-label">{tool.label}</span>
              </div>
            ))}
          </div>
        </div>
      ) : (
        // 对话页面
        <div className="chat-page">
          <div className="chat-messages">
            {messages.map((msg) => (
              <div key={msg.id} className={`message-item ${msg.type}`}>
                <Avatar
                  icon={msg.type === 'user' ? <UserOutlined /> : <RobotOutlined />}
                  style={{
                    backgroundColor: msg.type === 'user' ? '#1890ff' : '#52c41a',
                  }}
                />
                <div className="message-content">
                  <div className="message-bubble">
                    {msg.content}
                  </div>
                  <div className="message-time">{msg.time}</div>
                </div>
              </div>
            ))}

            {loading && (
              <div className="message-item ai">
                <Avatar icon={<RobotOutlined />} style={{ backgroundColor: '#52c41a' }} />
                <div className="message-content">
                  <div className="message-bubble loading">
                    <Spin size="small" />
                    <span style={{ marginLeft: 8 }}>AI正在思考...</span>
                  </div>
                </div>
              </div>
            )}

            <div ref={messagesEndRef} />
          </div>

          <div className="chat-input">
            <div className="input-box">
              <TextArea
                value={inputValue}
                onChange={(e) => setInputValue(e.target.value)}
                placeholder="发消息或输入 / 选择话题"
                autoSize={{ minRows: 1, maxRows: 4 }}
                bordered={false}
                onPressEnter={(e) => {
                  if (!e.shiftKey) {
                    e.preventDefault()
                    handleSend()
                  }
                }}
              />
              <div className="input-footer">
                <Space size="middle">
                  <Button type="text" icon={<PaperClipOutlined />} size="small" />
                  <Button type="text" size="small">深度思考</Button>
                </Space>
                <Space size="small">
                  <Button type="text" icon={<AudioOutlined />} size="small" />
                  <Button
                    type="primary"
                    shape="circle"
                    icon={<SendOutlined />}
                    onClick={handleSend}
                    disabled={loading || !inputValue.trim()}
                  />
                </Space>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default AITools
